﻿using UnityEngine;
using System.Collections;

public class TankMove : MonoBehaviour {

    public int PlayerNumber = 1;
    public float Speed = 1.35f;
    public float TurnSpeed = 180f;
    public IJoyStick joyStick;

    private string _moveAxisName;
    private string _turnAxisName;

    private float _moveInputValue;
    private float _turnInputValue;
    private Vector3 _directionInputValue;

    private Rigidbody _rigidBoddy;

    private void Awake()
    {
        _rigidBoddy = GetComponent<Rigidbody>();
    }

	private void OnEnable () {
        _rigidBoddy.isKinematic = false;
        _moveInputValue = 0f;
        _turnInputValue = 0f;
	}

    private void OnDisable()
    {
        _rigidBoddy.isKinematic = true;
    }
	
    void Start()
    {
        _moveAxisName = "Vertical" + PlayerNumber;
        _turnAxisName = "Horizontal" + PlayerNumber;
    }

	void Update () {
        //_moveInputValue = Input.GetAxis(_moveAxisName);
        //_turnInputValue = Input.GetAxis(_turnAxisName);

        //_moveInputValue = UIMaster.instance.inputHorizontal;
        //_turnInputValue = UIMaster.instance.inputDirection;

        if(joyStick!=null)
        {
            _moveInputValue = joyStick.inputMoveVal;
            _directionInputValue = joyStick.coarseDirection;
        }
    }

    //必须在FixedUpdate进行Move和Turn，否则移动会很不流畅
    void FixedUpdate()
    {
        Move(_moveInputValue);
        Turn(_directionInputValue);
    }

    public void Move(float moveValue)
    {
        Vector3 movement = transform.forward * moveValue * Speed * Time.deltaTime;
        if(movement!=Vector3.zero)
        {
            //_rigidBoddy.MovePosition(_rigidBoddy.position + movement);
            transform.position = transform.position + movement;
        }
    }

    public void Turn(int nextDir)
    {
        Vector3[] dirs = new Vector3[] { Vector3.forward, Vector3.back, Vector3.left, Vector3.right };
        Vector3 dir = dirs[nextDir % dirs.Length];
        Turn(dir);
    }

    public void Turn(Vector3 nextDir)
    {
        if (nextDir.magnitude == 0) return;

        float yRotation = 0;
        if (nextDir==Vector3.forward)
        {
            yRotation = 180f;
        }
        else if (nextDir==Vector3.back)
        {
            yRotation = 0;
        }
        else if(nextDir==Vector3.left){
            yRotation = 90f;
        }
        else
        {
            yRotation = 270f;
        }
        //Debug.Log("yRotation=" + yRotation);
        transform.rotation = Quaternion.Euler(0, yRotation, 0);
    }
}
